package com.a01_2021.thousandstimes.general.controller;


import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.entity.SysRole;
import com.a01_2021.thousandstimes.general.entity.SysUser;
import com.a01_2021.thousandstimes.general.jwt.JwtTokenUtil;
import com.a01_2021.thousandstimes.general.service.*;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author FRQ
 * @since 2021-02-22
 */
@RestController
@RequestMapping("/sys-user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    PersonnelInfomationService personnelInfomationService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private ExperienceService experienceService;


    //注册
    @DS("#header.instanceid")
    @PostMapping("register")
    public AjaxResponse register(@RequestBody(required = false) SysUser sysUser, @RequestHeader("instanceid") String instanceId) {
        try {
            return sysUserService.insertUser(sysUser, instanceId);
        } catch (Exception e) {
            return AjaxResponse.error("注册失败，请重新输入用户名和密码");
        }

    }

    /**
     * 通过userId与roleId集合设置对应用户角色
     *
     * @param userId      用户id
     * @param setRoleList 角色id
     * @return AjaxResponse
     * @throws CustomException 当用户不存在，角色不存在时抛出该异常
     */
    @PreAuthorize("hasAuthority('sys-user-setRole')")
    @DS("#header.instanceid")
    @PostMapping("setRole")
    public AjaxResponse setRole(long userId, @RequestParam(value = "setRoleList") Set<Long> setRoleList) throws CustomException {
        if (setRoleList.isEmpty()) {
            //若传入设定角色集为空
            return AjaxResponse.error(400, "传入设置角色集合不得为空");
        }
        Map<String, Object> resultMap = sysUserService.setRole(userId, setRoleList);
        return AjaxResponse.success(resultMap);
    }

    /**
     * 通过用户id查询其具有的角色
     *
     * @param userId 用户id
     * @return AjaxResponse
     * @throws CustomException 当用户不存在时抛出该异常
     */
    @PreAuthorize("hasAuthority('sys-user-getRole')")
    @DS("#header.instanceid")
    @PostMapping("getRole")
    public AjaxResponse getRole(long userId) throws CustomException {
        List<SysRole> roleList = sysRoleService.getRole(userId);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("userId", userId);
        resultMap.put("roleList", roleList);
        return AjaxResponse.success(resultMap);
    }

    /**
     * 通过角色id查询对应用户
     *
     * @param roleId 角色id
     * @return AjaxResponse
     * @throws CustomException 当角色不存在时抛出该异常
     */
    @PreAuthorize("hasAuthority('sys-user-getUserFromRole')")
    @DS("#header.instanceid")
    @PostMapping("getUserFromRole")
    public AjaxResponse getUserFromRole(long roleId) throws CustomException {
        List<SysUser> sysUserList = sysUserService.getUserFromRole(roleId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleId", roleId);
        resultMap.put("userList", sysUserList);
        return AjaxResponse.success(resultMap);
    }

    /**
     * 用于上传用户头像
     *
     * @param instanceId 实例id
     * @param file       文件
     * @return AjaxResponse
     * @throws CustomException 当文件后缀不符合要求时抛出
     * @throws IOException     IO异常
     */
    @PreAuthorize("hasAuthority('sys-user-uploadHeadPic')")
    @DS("#header.instanceid")
    @PostMapping("uploadHeadPic")
    public AjaxResponse uploadHeadPic(@RequestHeader("instanceid") String instanceId, @RequestHeader("${jwt.header}") String token, MultipartFile file) throws CustomException, IOException {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        SysUser user = sysUserService.uploadHeadPic(userId, instanceId, file);
        return AjaxResponse.success(user);
    }

    /**
     * 用于获取用户信息
     *
     * @param token jwt令牌
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('sys-user-getUserInfo')")
    @DS("#header.instanceid")
    @PostMapping("getUserInfo")
    public AjaxResponse getUserinfo(@RequestHeader("${jwt.header}") String token) throws CustomException {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", sysUserService.getInfo(userId));
        resultMap.put("name", personnelInfomationService.getName(userId));
        resultMap.put("title", experienceService.getCurrentTitle(userId));
        return AjaxResponse.success(resultMap);
    }
}
